package com.gift.recommendation.util;

import com.gift.recommendation.Base.PageData;
import com.github.pagehelper.Page;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class PageTransUtil {
    public PageTransUtil(){

    }
    public static <T> PageData<T> createPageList(Page sourcePage, Class<T> objClass){
        if (sourcePage == null) {
            return null;
        }else{
            PageData<T> pageList = new PageData();
            setPageInfo(pageList,sourcePage);
            List<T> items = new ArrayList();
            if(sourcePage.getResult() != null && sourcePage.getResult().size() > 0){
                sourcePage.getResult().stream().forEach(item ->{
                    try {
                        T object = objClass.newInstance();
                        BeanUtils.copyProperties(item,object);
                        items.add(object);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            pageList.setData(items);
            return pageList;
        }
    }

    public static <E> PageData<E> createPageList(Page<E> page) {
        if (page == null) {
            return null;
        } else {
            PageData<E> pageList = new PageData();
            setPageInfo(pageList, page);
            pageList.setData(page.getResult());
            return pageList;
        }
    }

    private static void setPageInfo(PageData pageList, Page page) {
        pageList.setCurrentPage(page.getPageNum());
        pageList.setPageSize(page.getPageSize());
        pageList.setLastPage(page.getPages());
        pageList.setTotal(Integer.valueOf(page.getTotal() + ""));
    }
}
